﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace CassiniRunner
{
    public partial class CassiniServer 
    {
        public Cassini.Server server = null;
        Mutex mutex = null;
        static string _appPath;
        static int _portNumber;
        static string _virtRoot;
        public CassiniServer()
        {
           
        }

        public  void Start(string[] args)
        {
            mutex = new Mutex(false, "mycassini" + _portNumber);
            if (mutex.WaitOne())
            {
                server = new Cassini.Server(_portNumber, "/", _appPath);
                server.Start();
                System.Diagnostics.Process.Start("http://localhost:" + _portNumber + "/Index.aspx");
            }
        }

        public void Stop()
        {
            if (mutex != null)
            {
                if (!mutex.WaitOne())
                {
                    mutex.ReleaseMutex();
                }
                server?.Stop();
            }
        }
        private static void ParseArgs(String[] args)
        {
            string portString = null;
            try
            {
                if (args.Length >= 1)
                {
                    _appPath = args[0].Trim();
                    if (_appPath[0] == '/')
                    {
                        _appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _appPath.Substring(1));
                    }
                }

                if (args.Length >= 2)
                    portString = args[1];

                if (args.Length >= 3)
                    _virtRoot = args[2];
            }
            catch
            {
            }

            if (portString == null)
                portString = "89";

            _portNumber = Int32.Parse(portString);
            if (_virtRoot == null)
                _virtRoot = "/";

            if (_appPath == null)
                _appPath = _appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WebFormApp");
        }
    }
}
